package com.ffyc.resale.component;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ffyc.resale.dao.ChatDao;
import com.ffyc.resale.model.Chat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 实现在线聊天
 */
@Component
public class MyWebSocketHandler extends TextWebSocketHandler {
    @Autowired
    ChatDao chatDao;
    // 存储所有连接的会话，key为用户ID
    private static final Map<Integer, WebSocketSession> userSessions = new ConcurrentHashMap<>();
    
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        System.out.println("新连接: " + session.getId());
        
        // 从URI中获取用户ID
        String uri = session.getUri().toString();
        String[] pathSegments = uri.split("/");
        int userId = Integer.parseInt(pathSegments[pathSegments.length - 2]);
        
        // 存储会话，以用户ID为键
        userSessions.put(userId, session);
        System.out.println("用户 " + userId + " 已连接，当前在线用户数: " + userSessions.size());
    }
    
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        System.out.println("收到消息: " + message.getPayload() + " 来自: " + session.getId());
        
        // 解析JSON消息
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(message.getPayload());
        String content = jsonNode.get("content").asText();
        int receiver = jsonNode.get("receiver").asInt();
        int sender = jsonNode.get("sender").asInt();
        
        // 保存消息到数据库
        Chat chat = new Chat();
        chat.setContent(content);
        chat.setReceiver(receiver);
        chat.setSender(sender);
        chat.setTime(new Date());
        chatDao.insert(chat);
        
        // 转发消息给接收者
        WebSocketSession receiverSession = userSessions.get(receiver);
        if (receiverSession != null && receiverSession.isOpen()) {
            // 构建回复消息，包含消息ID
            JsonNode responseNode = objectMapper.createObjectNode()
                    .put("id", chat.getId())
                    .put("sender", sender)
                    .put("receiver", receiver)
                    .put("content", content)
                    .put("timestamp", System.currentTimeMillis());
            
            receiverSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(responseNode)));
            System.out.println("消息已转发给用户 " + receiver);
        } else {
            System.out.println("接收者 " + receiver + " 不在线，无法转发消息");
        }
        
        // 发送确认消息给发送者
        session.sendMessage(new TextMessage("服务器已收到消息: " + message.getPayload()));
    }
    
    @Override
    public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) {
        System.out.println("连接关闭: " + session.getId() + ", 状态: " + status);
        
        // 从URI中获取用户ID
        String uri = session.getUri().toString();
        String[] pathSegments = uri.split("/");
        int userId = Integer.parseInt(pathSegments[pathSegments.length - 2]);
        
        // 移除会话
        userSessions.remove(userId);
        System.out.println("用户 " + userId + " 已断开连接，剩余在线用户数: " + userSessions.size());
    }
    
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        System.out.println("传输错误: " + session.getId() + ", 异常: " + exception.getMessage());
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}